
import java.util.HashMap;
import java.util.ArrayList;

public class ChatWatcher extends Thread {

    private ChatManager manager;
    private ArrayList<ChatFile> openChats;
    private HashMap oldState = new HashMap<ChatFile, Long>();

    public ChatWatcher(ChatManager manager) {
        super();
        this.manager = manager;
        openChats = manager.getOpenChats();
    }

    @Override
    public void run() {
        while (true) {

            if (openChats.isEmpty() == false) {
                checkForChanges();
            }

            try {
                sleep(1000); // check updates every second
            } catch (InterruptedException ex) {
                // who cares?
            }

        }
    }

    // check if the file has been modified since the last check
    public void checkForChanges() {
        for (int i = 0; i < openChats.size(); i++) {
            ChatFile chat = openChats.get(i);
            long timeModified = chat.lastModified();
            Long oldTimeModified = (Long) oldState.get(chat.getName());

            if (oldTimeModified == null) {
                updateFileState(chat);
            } else if (timeModified != oldTimeModified && timeModified != 0) {
                updateFileState(chat);
                manager.update(chat);
            }
        }
    }

    private void updateFileState(ChatFile chat) {
        oldState.put(chat.getName(), chat.lastModified());
    }
}
